package pe.gob.inei.fx.lib.component.manager
{
	import flash.events.EventDispatcher;
	
	import mx.containers.Canvas;
	import mx.containers.ViewStack;
	import mx.controls.Alert;
	import mx.events.FlexEvent;
	
	import pe.gob.inei.fx.lib.component.Pod;
	import pe.gob.inei.fx.lib.component.events.PodStateChangeEvent;
	import pe.gob.inei.fx.lib.component.items.PodItem;
	
	public class PodManager extends EventDispatcher {
		
		private static var _instance:PodManager;
		
		public function PodManager(singleton:SingletonForce) {
			addEventListener(PodStateChangeEvent.CLOSE, closePodEventHandler);
		}
		
		public static function instance():PodManager {
			if(PodManager._instance == null)
				PodManager._instance = new PodManager(new SingletonForce());
			return PodManager._instance;
		}
		
		private var layoutManagers:Object = new Object();
		private var currentLayuotManager:PodLayoutManager;
		private var podHash:Object = new Object();
		private var pods:Array = new Array();
		
		private var viewStackContent:ViewStack;
		
		[Bindable]
		public function set viewStack(value:ViewStack):void {
			viewStackContent = value;
		}
		
		public function get viewStack():ViewStack {
			return viewStackContent;
		}
		
		//FUNCION AGREGAR
		public function addPod(pod:PodItem, viewId:String):void {
			if(pods[viewId] == null)
				pods[viewId] = new Object();
			if(pods[viewId][pod.id] != null)
				return;
			if(layoutManagers[viewId] == null) {
				var canvas:Canvas = new Canvas();
				canvas.horizontalScrollPolicy = "off";
				canvas.verticalScrollPolicy = "off";
				canvas.percentWidth = 100;
				canvas.percentHeight = 100;
				
				viewStack.addChild(canvas);
				
				var layuotManager:PodLayoutManager = new PodLayoutManager();
				layuotManager.id = viewId;
				layuotManager.container = canvas;
				layoutManagers[viewId] = layuotManager;
			}
			currentLayuotManager = layoutManagers[viewId] as PodLayoutManager;
			
			var miPod:Pod = new Pod();
			miPod.id = pod.id;
			miPod.isClosable = pod.isClosable;
			miPod.title = pod.titulo;
			miPod.addChild(pod.view);
			miPod.layoutManager = currentLayuotManager;
			
			pods[viewId][pod.id] = miPod;
			
			var index:Number = currentLayuotManager.items.length;
			currentLayuotManager.addItemAt(miPod, index);
			
			podHash[miPod] = currentLayuotManager;
			
			miPod.addEventListener(FlexEvent.UPDATE_COMPLETE, onCreationCompletePod);
		}
		
		//EVENTO QUITAR
		private function closePodEventHandler(event:PodStateChangeEvent):void {
			var pod:Pod = event.pod;
			pods[pod.layoutManager.id][pod.id] = null;
		}
		
		private function onCreationCompletePod(e:FlexEvent):void {
			e.currentTarget.removeEventListener(FlexEvent.UPDATE_COMPLETE, onCreationCompletePod);
			var manager:PodLayoutManager = PodLayoutManager(podHash[e.currentTarget]);
			manager.removeNullItems();
			manager.updateLayout(true);
		}
	}
}

class SingletonForce{}